package xyz.xpman.prisonerfitness.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * bitmap util
 */
@SuppressWarnings("unused")
public class BitmapUtil {

    /**
     * 读取 bitmap
     *
     * @return bitmap
     */
    public static Bitmap readBitmap(@NotNull String fileName) {
        Bitmap bitmap = null;
        try {
            if (FileUtil.isFileExists(fileName)) {
                bitmap = BitmapFactory.decodeStream(new FileInputStream(fileName));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 读取 bitmap
     *
     * @return bitmap
     */
    public static Bitmap readBitmap(@NotNull InputStream inputStream) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    /**
     * 保存 bitmap
     * @param bitmap bitmap
     * @param filePath 文件名
     * @param format 格式
     * @return success
     */
    public static boolean writeBitmap(@NotNull Bitmap bitmap,
                                      @NotNull String filePath,
                                      @NotNull Bitmap.CompressFormat format) {

        boolean success = false;
        File file = new File(filePath);


        if (FileUtil.createFile(file)) {
            try (FileOutputStream out = new FileOutputStream(file, false)) {

                success = bitmap.compress(format, 100, out);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return success;
    }

}